import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/company_dynamic_entity.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/icon_text_view.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

/// 变更信息
class CompanyChangePage extends StatefulWidget {
  final String companyKey;
  final String companyName;

  const CompanyChangePage({Key key, this.companyKey, this.companyName})
      : super(key: key);

  @override
  _CompanyChangePageState createState() => _CompanyChangePageState();
}

class _CompanyChangePageState extends State<CompanyChangePage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  int page = AppConfig.page;

  /// 列表数据
  List<CompanyDynamicContentEntity> _dataLists = [];

  Future _future;

  LoadState _loadState = LoadState.State_Loading;

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }
    setState(() {
      _future = _getList();
    });
  }

  /// 对外投资
  Future<ApiResponse<CompanyDynamicEntity>> _getList() async {
    return await ApiHome.companyChange<CompanyDynamicEntity>(
        companyKey: widget.companyKey,
        companyName: widget.companyName,
        page: page);
  }

  /// 对外投资
  FutureBuilder<ApiResponse<CompanyDynamicEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<CompanyDynamicEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              CompanyDynamicEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.content == null ? [] : entity.content;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_refreshController.isLoading) {
              _refreshController.loadComplete();
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _buildFutureBuilder());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("变更信息", style: FonStyle.navTextStyle()));
  }

  /// 列表
  Widget _initList() {
    return Padding(
        padding: EdgeInsets.symmetric(vertical: ScreenAdapter.height(20)),
        child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: _refresh,
            onLoading: _refresh,
            child: ListView.separated(
              itemCount: _dataLists.length,
              itemBuilder: (BuildContext context, int index) {
                CompanyDynamicContentEntity model = _dataLists[index];
                return _getCell(data: model);
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  color: ThemeColors.colorType49,
                );
              },
            )));
  }

  /// 列表cell
  Widget _getCell({CompanyDynamicContentEntity data}) {
    return Container(
        margin: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            color: ThemeColors.colorWhite,
            border: Border.all(color: ThemeColors.colorType45, width: 0.5),
            borderRadius: BorderRadius.circular(ScreenAdapter.width(15))),
        child: Column(children: [
          Container(
            height: ScreenAdapter.height(60),
            // margin: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
            padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
                color: ThemeColors.colorType6,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(ScreenAdapter.width(15)),
                    topRight: Radius.circular(ScreenAdapter.width(15)))),
            child: IconText(
              " " + data.date ?? "-",
              icon: Image.asset(RPath.imgPath + "icon_time_white.png",
                  fit: BoxFit.contain,
                  width: ScreenAdapter.width(26),
                  height: ScreenAdapter.width(26)),
              padding: EdgeInsets.only(right: ScreenAdapter.width(5)),
              style: TextStyle(
                color: ThemeColors.colorWhite,
                fontSize: ScreenAdapter.sp(26),
              ),
            ),
          ),
          Container(
              padding: EdgeInsets.all(ScreenAdapter.width(30)),
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: _getChildItem(data)))
        ]));
  }

  List<Widget> _getChildItem(CompanyDynamicContentEntity entity) {
    return entity.content
        .map((e) => Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Text(
                      "变更事项：",
                      style: TextStyle(
                          color: ThemeColors.colorType14,
                          fontSize: ScreenAdapter.sp(30)),
                      maxLines: 1,
                    ),
                    Expanded(
                        child: Text(
                      e.bgsx,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30)),
                    ))
                  ]),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Text(
                      "    变更前：",
                      style: TextStyle(
                          color: ThemeColors.colorType14,
                          fontSize: ScreenAdapter.sp(30)),
                      maxLines: 1,
                    ),
                    Expanded(
                        child: Text(
                      e.bgq,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30)),
                    ))
                  ]),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
                    Text(
                      "    变更后：",
                      style: TextStyle(
                          color: ThemeColors.colorType14,
                          fontSize: ScreenAdapter.sp(30)),
                      maxLines: 1,
                    ),
                    Expanded(
                        child: Text(
                      e.bgh,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30)),
                    ))
                  ]),
                  Container(
                    margin: EdgeInsets.only(bottom: ScreenAdapter.height(40)),
                    width: double.infinity,
                    height: 1,
                  )
                ]))
        .toList();
  }
}
